//
//  LoginViewController.m
//  宜居HD
//
//  Created by 张金国 on 16/4/25.
//  Copyright © 2016年 张金国. All rights reserved.
//

#import "LoginViewController.h"
#import "Masonry.h"
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "YJSplitViewController.h"
#import "LoginRectView.h"
#import "ForgetPassWordController.h"
#import "IQKeyboardManager.h"
#import "AppDelegate+ProjectEnterConfig.h"
#import "NetworkingBaseManager.h"
#import "NetworkingAESManager.h"
#import "NetWorkingManagerFactory.h"
#import "HeaderUtil.h"
#import "RequestGenerator.h"
#import "AESUtil.h"
#import "AppContext.h"
#import "NSString+Validate.h"
#import "UIAlertControllerUtil.h"
#import "CoreDataUtil.h"

@interface LoginViewController ()<NetworkingBaseManagerAPISuccessCallbackDelegate, NetworkingBaseManagerValidator>
/**
 *  容器视图
 */
@property (nonatomic, strong)UIView       *containerView;
/**
 *  头像
 */
@property (nonatomic, strong)UIImageView  *headerimageView;
/**
 *  用户名框
 */
@property (nonatomic ,strong)LoginRectView *userNameView;


@property (nonatomic, strong)UITextField *userNameFeild;
/**
 *  密码框
 */
@property (nonatomic ,strong)LoginRectView *passWordView;


@property (nonatomic, strong)UITextField *pasWordFeild;
/**
 *  登录按钮
 */
@property (nonatomic, strong)UIButton     *loginButton;
/**
 *  记住密码
 */
@property (nonatomic ,strong)UIButton     *remeberButton;
/**
 *  忘记密码？
 */
@property (nonatomic ,strong)UIButton     *forgetButton;

@property (nonatomic, strong)NetworkingBaseManager *manager;

@property (nonatomic ,strong)NetworkingBaseManager *manager1;

@end

@implementation LoginViewController
{
    UIAlertController  *_alertController;
}
#pragma mark - LifeCircle

- (void)loadView {
    self.view = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"LoginBack"]];
    self.view.userInteractionEnabled = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutUI];
   
}
#pragma mark - Private

- (void)layoutUI {
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
        make.width.equalTo(self.view.mas_width).multipliedBy(1.0/3.0f);
        make.height.equalTo(self.view.mas_height).multipliedBy(4.0/9.0f);
    }];
    [self.headerimageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.containerView.mas_top);
        make.height.width.equalTo(self.containerView.mas_width).multipliedBy(1.0/3.0f);
        make.centerX.equalTo(self.containerView.mas_centerX);
    }];
    [self.userNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerimageView.mas_bottom).offset(10);
        make.left.equalTo(self.containerView.mas_left);
        make.width.equalTo(self.containerView.mas_width);
        make.height.equalTo(self.containerView.mas_height).multipliedBy(1/7.0f);
    }];
    [self.passWordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.userNameView.mas_bottom).offset(10);
        make.left.equalTo(self.containerView.mas_left);
        make.width.equalTo(self.containerView.mas_width);
        make.height.equalTo(self.containerView.mas_height).multipliedBy(1/7.0f);
    }];
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.left.equalTo(self.containerView);
        make.height.equalTo(self.containerView.mas_height).multipliedBy(2/13.0);
    }];
    [self.remeberButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.containerView.mas_bottom).offset(10);
        make.left.equalTo(self.containerView.mas_left);
        make.width.equalTo(self.containerView.mas_width).multipliedBy(1/2.0f);
        make.height.equalTo(@40);
    }];
    [self.forgetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.containerView.mas_bottom).offset(10);
        make.right.equalTo(self.containerView.mas_right);
        make.width.equalTo(self.containerView.mas_width).multipliedBy(1/3.0f);
        make.height.equalTo(@40);
    }];
    
}


#pragma mark - NetworkingBaseManagerValidator
- (BOOL)isCorrectWithParamsData:(NSDictionary *)data{
    NSString *userName = [data objectForKey:@"userName"];
    NSString *password = [data objectForKey:@"password"];
    
    if ([userName validateUserName]==YES && [password validatePasswordStrenth]!=PasswordStrengthInvalid) {
        return YES;
    } else {
        [UIAlertControllerUtil generateInfoControllerWithTitle:@"错误" message:@"用户名或密码格式错误"];
        return NO;
    }
}

- (BOOL)isCorrectWithCallbackData:(NSDictionary *)data{
    NSInteger stateCode = [[data objectForKey:@"stateCode"] integerValue];
    
    if (stateCode != 100) {
        NSString *stateMessage = [data objectForKey:@"stateMessage"];
        [UIAlertControllerUtil generateInfoControllerWithTitle:@"错误" message:stateMessage];
        return NO;
    } else {
        return YES;
    }
}

#pragma mark - NetworkingBaseManagerAPISuccessCallbackDelegate
- (void)manager:(NetworkingBaseManager *)manager callAPIDidSuccessWithParams:(NSDictionary *)responseParams{
    if (manager == self.manager1) {
        
        NSDictionary *responseData = [responseParams objectForKey:@"data"];
        DDLogInfo(@"responseData----------%@",responseData);
        if ([responseData  isEqual: @1]) {
            ForgetPassWordController *forgetPassWordController = [[ForgetPassWordController alloc]init];
            [self presentViewController:forgetPassWordController animated:YES completion:nil];
        }else {
            [UIAlertControllerUtil generateInfoControllerWithTitle:@"提示" message:@"请检查你的账户是否正确？"];
        }
    }else if(manager == self.manager){
        NSDictionary *responseData = [responseParams objectForKey:@"data"];
        NSDictionary *requestParams = manager.params;
        NSString *AESPassword = [requestParams objectForKey:@"password"];
        NSString *iv = ((NetworkingAESManager *)self.manager).iv;
        NSString *password = [AESUtil decryptAESData:AESPassword withKey:@"HJvkWaP8FE2fTDfm" andIV:iv];
        NSString *responseIv = [responseData objectForKey:@"iv"];
        NSInteger userId = [[responseData objectForKey:@"salerId"] integerValue];
        NSInteger projectId = [[responseData objectForKey:@"projectId"] integerValue];
        NSString *encriptToken = [responseData objectForKey:@"encriptToken"];
        NSString *hxUserName = [responseData objectForKey:@"hxAccount"];
        NSString *token = [AESUtil decryptAESData:encriptToken withKey:@"hr3JT0R4HA8A5Uty" andIV:responseIv];
        AppContext *appContext = [AppContext sharedInstance];
        appContext.userId = userId;
        appContext.projectId = projectId;
        appContext.appToken = token;
        [self hxLogin:hxUserName password:password];
    }
}

- (void)hxLogin:(NSString *)userName password:(NSString *)password{
    [self goToMainViewControllerEvent];
    
//    __weak typeof(self) weakSelf = self;
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        EMError *error = [[EMClient sharedClient] loginWithUsername:userName password:password];
//        dispatch_async(dispatch_get_main_queue(), ^{
////            [weakSelf hideHud];
//            if (!error) {
//                //设置是否自动登录
////                [[EMClient sharedClient].options setIsAutoLogin:YES];
//                //获取数据库中数据
////                [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
//                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
////                    [[EMClient sharedClient] dataMigrationTo3];
//                    dispatch_async(dispatch_get_main_queue(), ^{
////                        [[ChatDemoHelper shareHelper] asyncGroupFromServer];
////                        [[ChatDemoHelper shareHelper] asyncConversationFromDB];
////                        [[ChatDemoHelper shareHelper] asyncPushOptions];
////                        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
//                        //保存最近一次登录用户名
//                        //[weakself saveLastLoginUsername];
//                        
////                        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
//                        [self goToMainViewControllerEvent];
//                    });
//                });
//            } else {
//                switch (error.code)
//                {
//                    case EMErrorNetworkUnavailable:
//                        TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
//                        break;
//                    case EMErrorServerNotReachable:
//                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
//                        break;
//                    case EMErrorUserAuthenticationFailed:
//                        TTAlertNoTitle(error.errorDescription);
//                        break;
//                    case EMErrorServerTimeout:
//                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
//                        break;
//                    default:
//                        TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Login failure"));
//                        break;
//                }
//            }
//        });
//    });
}

#pragma mark - privite method
- (void)loginWithUserName:(NSString *)userName passWord:(NSString *)passWord {
    NSString *iv = [HeaderUtil genIVParameter];
    self.manager = [NetworkingManagerFactory generateAESManager:iv];
    self.manager.successDelegate = self;
    self.manager.validator = self;
    NSString *AESPassword = [AESUtil encryptAESData:passWord withKey:@"HJvkWaP8FE2fTDfm" andIV:iv];
    NSDictionary *requestParams = @{
                                    @"userName" : userName,
                                    @"password" : AESPassword
                                    };
    NSString *apiName = [[RequestGenerator sharedInstance] generateCommonApiWithName:@"salers/login"];
    self.manager.apiName = apiName;
    self.manager.params = requestParams;
    self.manager.requestType = HTTP_POST;
    [self.manager loadRequest];
}

- (void)changePassword:(NSString *)textString {
    self.manager1 = [NetworkingManagerFactory generateNormalManager];
    self.manager1.apiName = [[RequestGenerator sharedInstance] generateCommonApiWithName:@"salers/account"];
    self.manager1.successDelegate = self;
    self.manager1.params = @{@"account":textString};
    self.manager1.requestType = HTTP_GET;
    [self.manager1 loadRequest];
}
//跳转
- (void)goToMainViewControllerEvent {
    YJSplitViewController* splitViewController = [[YJSplitViewController alloc]init];
    [self presentViewController:splitViewController animated:YES completion:nil];
}

#pragma mark - event response
//登陆按钮事件
- (void)loginButtonEvent {
    [self loginWithUserName:_userNameFeild.text passWord:_pasWordFeild.text];
//    [self goToMainViewControllerEvent];
}

- (void)remeberButtonEvent:(UIButton *)button {
    button.selected = !button.selected;
    
    if (button.selected == NO) {
        //清除密码和账号
    }else {
        //缓存密码和账号
    }
}

- (void)forgetButtonEvent:(UIButton *)button {
    [AppDelegate shutOffKeyBoard];
    [self createAlertController];
}

- (void)createAlertController {
    _alertController = [UIAlertController alertControllerWithTitle:@"找回密码" message:@"请输入你登录的账号" preferredStyle:UIAlertControllerStyleAlert];
    __weak __typeof__(self) weakSelf = self;
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.view endEditing:YES];
        UITextField *account = _alertController.textFields.firstObject;
        NSLog(@"%@",_alertController.textFields.firstObject);
        if ([account.text isEqualToString:@""]) {
            [UIAlertControllerUtil generateInfoControllerWithTitle:@"提示" message:@"账号不能不为空"];
        }else {
            [weakSelf changePassword:account.text];
        }
         [AppDelegate ConfigKeyBoard];
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        DDLogInfo(@"取消");
    }];
    [_alertController addAction:sureAction];
    [_alertController addAction:cancleAction];
    [_alertController addTextFieldWithConfigurationHandler:nil];
    [self presentViewController:_alertController animated:YES completion:nil];
}

#pragma mark - Getter
- (UIView *)containerView {
    if (!_containerView) {
        _containerView = [[UIView alloc]init];
        [self.view addSubview:_containerView];
    }
    return _containerView;
}
- (UIImageView *)headerimageView {
    if (!_headerimageView) {
        _headerimageView = [[UIImageView alloc]init];
        _headerimageView.layer.masksToBounds = YES;
        _headerimageView.layer.cornerRadius = 1/2.0f;
        _headerimageView.image = [UIImage imageNamed:@"Loginlogo"];
        [self.containerView addSubview:_headerimageView];
    }
    return _headerimageView;
}
- (UIButton *)loginButton {
    if (!_loginButton) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.backgroundColor = [UIColor colorWithRed:0.745 green:0.251 blue:0.224 alpha:0.730];
        _loginButton.layer.masksToBounds = YES;
        _loginButton.layer.cornerRadius = 5.0f;
        [_loginButton setTitleColor:[UIColor colorWithRed:0.898 green:0.941 blue:0.941 alpha:1.000] forState:UIControlStateNormal];
        [_loginButton setTitle:@"用户登录" forState:UIControlStateNormal];
        [_loginButton addTarget:self action:@selector(loginButtonEvent) forControlEvents:UIControlEventTouchUpInside];
        [self.containerView addSubview:_loginButton];
    }
    return _loginButton;
}
- (UIButton *)remeberButton {
    if (!_remeberButton) {
        _remeberButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_remeberButton setTitle:@"记住密码" forState:UIControlStateNormal];
        [_remeberButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 100)];
        [_remeberButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -70, 0, 0)];
        [_remeberButton setImage:[UIImage imageNamed:@"remember_Do"] forState:UIControlStateNormal];
        [_remeberButton setImage:[UIImage imageNamed:@"remember"] forState:UIControlStateSelected];
        [_remeberButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
        [_remeberButton  addTarget:self action:@selector(remeberButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_remeberButton];
    }
    return _remeberButton;
}
- (UIButton *)forgetButton {
    if (!_forgetButton) {
        _forgetButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_forgetButton setTitle:@"忘记密码？" forState:UIControlStateNormal];
        [_forgetButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -25)];
        [_forgetButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
        [_forgetButton  addTarget:self action:@selector(forgetButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_forgetButton];
    }
    return _forgetButton;
}
- (LoginRectView *)userNameView {
    if (!_userNameView) {
        _userNameView = [[LoginRectView alloc]init];
        _userNameView.imageUrl = @"账号";
        for (UITextField *textf in _userNameView.subviews) {
            if ([textf isKindOfClass:[UITextField class]]) {
                _userNameFeild = textf;
                _userNameFeild.text = @"18382427378";
            }
        }
        [self.containerView addSubview:_userNameView];
    }
    return _userNameView;
}
- (LoginRectView *)passWordView {
    if (!_passWordView) {
        _passWordView = [[LoginRectView alloc]init];
        _passWordView.imageUrl = @"密码";
        for (UITextField *textf in _passWordView.subviews) {
            if ([textf isKindOfClass:[UITextField class]]) {
                _pasWordFeild = textf;
                _pasWordFeild.text = @"18382427378";
            }
        }
        [self.containerView addSubview:_passWordView];
    }
    return _passWordView;
}

@end
